package com.apps.ftapp;

import android.annotation.TargetApi;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.allenliu.versionchecklib.core.http.HttpParams;
import com.allenliu.versionchecklib.core.http.HttpRequestMethod;
import com.apps.ftapp.act.CustomDialogActivity;
import com.apps.ftapp.activity.ABeseActivity;
import com.apps.ftapp.bean.UserInfo;
import com.apps.ftapp.fragment.AccountFragment;
import com.apps.ftapp.fragment.LessonFragment;
import com.apps.ftapp.fragment.NewHomeFragment2;
import com.apps.ftapp.fragment.SubjectFragment;
import com.apps.ftapp.service.MyService1;
import com.apps.ftapp.util.AppUtils;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.PrivateTabHost;
import com.apps.ftapp.util.SharedPreferencesUtil;
import com.apps.ftapp.util.StatusBarUtils;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

public class MainActivity extends ABeseActivity implements NewHomeFragment2.CallBack {


    /**
     * FragmentTabhost
     */
    private PrivateTabHost mTabHost;
    public static MainActivity activity;
    /**
     * Fragment数组界面
     */
    private Class mClass[] = {NewHomeFragment2.class, LessonFragment.class,
            SubjectFragment.class, AccountFragment.class};

    private List<Fragment> mFragmentList;

    private Fragment mFragment[] = {new NewHomeFragment2(),
            new LessonFragment(),
            new SubjectFragment(),
            new AccountFragment()};

    /**
     * 选修卡文字
     */
    private String mTitles[] = {"首页", "课程", "题库", "我的"};

    /**
     * 选项呀图片
     */
    private int mImages[] = {
            R.drawable.index_tab_index,
            R.drawable.index_tab_lesson,
            R.drawable.index_tab_subject,
            R.drawable.index_tab_account
    };
    private long firstTime = 0;
    public static boolean isForeground = false;
    private final Gson gson = new Gson();

//    private NoScrollViewPager mViewPager;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initEvent();

        int curVersion = AppUtils.getLocalVersion(getApplicationContext());
        HttpParams params = new HttpParams();
        params.put("v", curVersion);
        VersionParams.Builder builder = new VersionParams.Builder().setRequestUrl(Constant.BASE_URL + "my/andsj")
                .setRequestParams(params)
                .setCustomDownloadActivityClass(CustomDialogActivity.class)
                .setService(MyService1.class)
                .setRequestMethod(HttpRequestMethod.POST);
        AllenChecker.startVersionCheck(getApplication(), builder.build());
        activity = this;
        Constant.FLAG = 0;
//


        String yijiName1111 = SharedPreferencesUtil.getData(getApplicationContext(), "yijiName", "") + "";
        if ("".equals(yijiName1111)) {
            SharedPreferencesUtil.saveData(getApplicationContext(), "yijiName", "教师资格证");
        }


        //创建数据库
//        Connector.getDatabase();
        getAndroiodScreenProperty();
        SQLiteDatabase db = Connector.getDatabase();
        getinfo();
    }

    /*@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //JPushInterface.init(getApplicationContext());
//        UltimateBar.newImmersionBuilder()
//                .applyNav(true)         // 是否应用到导航栏
//                .build(this)
//                .apply();

        initView();
        initEvent();


//        // 4.4及以上版本开启
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setTranslucentStatus(true);
//        }
//
//        SystemBarTintManager tintManager = new SystemBarTintManager(this);
//        tintManager.setStatusBarTintEnabled(true);
//        tintManager.setNavigationBarTintEnabled(true);
//        // 自定义颜色
//        tintManager.setTintColor(Color.parseColor("#ffffff"));


        int curVersion = AppUtils.getLocalVersion(getApplicationContext());
        HttpParams params = new HttpParams();
        params.put("v", curVersion);
        VersionParams.Builder builder = new VersionParams.Builder().setRequestUrl(Constant.BASE_URL + "my/andsj")
                .setRequestParams(params)
                .setCustomDownloadActivityClass(CustomDialogActivity.class)
                .setService(MyService1.class)
                .setRequestMethod(HttpRequestMethod.POST);
        AllenChecker.startVersionCheck(getApplication(), builder.build());
        activity = this;
        Constant.FLAG = 0;
//


        String yijiName1111 = SharedPreferencesUtil.getData(getApplicationContext(), "yijiName", "") + "";
        if ("".equals(yijiName1111)) {
            SharedPreferencesUtil.saveData(getApplicationContext(), "yijiName", "教师资格证");
        }


        //创建数据库
//        Connector.getDatabase();
        getAndroiodScreenProperty();
        SQLiteDatabase db = Connector.getDatabase();
        getinfo();
    }
*/
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    Toasty.normal(getApplicationContext(), "再按一次退出程序").show();
                    firstTime = secondTime;
//                    finish();
                    return true;
                } else {
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }


    /**
     * 实例化视图
     */

    private void initView() {

        StatusBarUtil.setTranslucentForImageViewInFragment(MainActivity.this, 0, null);
        StatusBarUtils.StatusBarLightMode(this);

        mTabHost = findViewById(android.R.id.tabhost);
//        mViewPager = (NoScrollViewPager) findViewById(R.id.view_pager);

//        mViewPager.setOffscreenPageLimit(3);

        mFragmentList = new ArrayList<>();

        mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
        mTabHost.getTabWidget().setDividerDrawable(null);

        for (int i = 0; i < mFragment.length; i++) {
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTitles[i]).setIndicator(getTabView(i));
            mTabHost.addTab(tabSpec, mClass[i], null);
            mFragmentList.add(mFragment[i]);
            mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
        }


    }

    /**
     * @param index
     * @return
     */
    private View getTabView(int index) {

        View view = LayoutInflater.from(this).inflate(R.layout.tab_item_view, null);

        ImageView image = view.findViewById(R.id.image);
        TextView title = view.findViewById(R.id.title);

        image.setImageResource(mImages[index]);
        title.setText(mTitles[index]);

        return view;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }


    private void initEvent() {

        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                int postion = mTabHost.getCurrentTab();
                switch (postion) {
                    case 0:
                        setTitle("首页");
//                        mViewPager.setCurrentItem(mTabHost.getCurrentTab());
                        break;
                    case 1:
//                        mViewPager.setCurrentItem(mTabHost.getCurrentTab());
                        break;
                    case 2:
                        setTitle("题库");
//                        mViewPager.setCurrentItem(mTabHost.getCurrentTab());
                        break;
                    case 3:
                        setTitle("图书");
//                        mViewPager.setCurrentItem(mTabHost.getCurrentTab());
                        break;
                    case 4:
                        setTitle("我的");
//                        mViewPager.setCurrentItem(mTabHost.getCurrentTab());
                        break;
                }

            }
        });


    }

    //for receive customer msg from jpush server
    //private MessageReceiver mMessageReceiver;
    //public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
//    public static final String MESSAGE_RECEIVED_ACTION = "com.ftapp.MESSAGE_RECEIVED_ACTION";
//    public static final String KEY_TITLE = "title";
//    public static final String KEY_MESSAGE = "message";
//    public static final String KEY_EXTRAS = "extras";

//    public void registerMessageReceiver() {
//        mMessageReceiver = new MessageReceiver();
//        IntentFilter filter = new IntentFilter();
//        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
//        filter.addAction(MESSAGE_RECEIVED_ACTION);
//        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
//    }
//
//    public class MessageReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            try {
//                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
//                    String messge = intent.getStringExtra(KEY_MESSAGE);
//                    String extras = intent.getStringExtra(KEY_EXTRAS);
//                    StringBuilder showMsg = new StringBuilder();
//                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
//                    if (!extras.isEmpty()) {
//                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
//                    }
//                    Toast.makeText(MainActivity.this, showMsg.toString(), Toast.LENGTH_SHORT);
//                }
//            } catch (Exception e) {
//            }
//        }
//    }

    /**
     * 回调
     *
     * @param str
     */
    @Override
    public void getData(String str) {
        L.i("main", ":::::::::::" + str);
        if ("课程".equals(Tools.isNull(str))) {
            mTabHost.setCurrentTab(1);
        } else if ("题库".equals(Tools.isNull(str))) {
            mTabHost.setCurrentTab(2);
        } else {
            //跳转到
//            ActivitySkipUtil.skipAnotherActivity(getActivity(), ZhenTiActivity.class,false);
        }
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }


    private void getinfo() {
        RequestParams params = new RequestParams();
        params.put("userId", Constant.uid);
        Async.post("getinfo", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    UserInfo result = gson.fromJson(new String(responseBody), UserInfo.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        Constant.token = result.getToken();
                        Constant.uid = result.getUid();
                        Constant.nickname = result.getNickname();
                    } else {
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    public void getAndroiodScreenProperty() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;// 屏幕宽度（像素）
        int height = dm.heightPixels; // 屏幕高度（像素）
        float density = dm.density;//屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;//屏幕密度dpi（120 / 160 / 240）
        //屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);//屏幕宽度(dp)
        Constant.SCREEN_WIDTH = screenWidth;
        //int screenHeight = (int) (height / density);//屏幕高度(dp)
    }


}